// pages/member//distribution/distribution.js
import { getInfo as memberInfo } from '../../../api/shareCenter'
import { list } from '../../../api/matchPoint'
import css2canvas from "../../../utils/css2canvas"
const util = require('../../../utils/util.js')

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    avatar: '',
    pageSize: 1000,
    isRuleShow: false,
    dialogShow: false,
    memberInfo: {matchPoint:'0'},
    canvasType: false,
    canvasHeight: 400,
    canvasH: 0,
    qrcode: '',
    carvasQrCode:'',
    carvasLogo:'',
    cardInfo: {
      TagText: "****", //标签
      Name: '****', //姓名
      avater: "", //需要https图片路径
      qrCode: "", //需要https图片路径
      price: '**',
      logo: 'http://cdnx.rzico.com/images/canvasMyLogo.png',
      coupons:'',
      marketPrice:'',
      activityPrice:''
    },
    oneButton: [{
      text: '确定'
    }],
    showOneButtonDialog: false,
    detailedList: []
  },
  
  loadPromoter() {
    memberInfo().then(res => {
      this.data.memberInfo = res.data
      this.setData({
        memberInfo: this.data.memberInfo
      })
    })
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading()
    this.data.pageNum = 1
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      this.loadPoint()
      wx.stopPullDownRefresh()
    }, 1000);
  },

  onReachBottom() {
    this.data.pageNum += 1
    this.loadPoint()
  },

  formatDate2Time(val) {
    let date = new Date(val);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + MM + '-' + d + " " + h + ":" + m + ":" + s;
  },
  loadPoint() {
    if (this.data.pageNum == 1) {
      this.data.detailedList = []
    }
    list({
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum
    }).then(res => {
      res.data.data.forEach(item => {
        item.createDate = this.formatDate2Time(item.createDate)
        item.thumbnail = 'http://cdn.rzico.com/v4.0/wallet-consumption.png'
        this.data.detailedList.push(item)
      })
      this.setData({
        detailedList: this.data.detailedList

      })
    })
  },
  invitationClick() {


  },
 
  toRule() {
    this.setData({
      isRuleShow: true
    })
  },
  ruleClick() {
    this.setData({
      isRuleShow: false
    })
  },
  tapDialogButton() {
    this.setData({
      showOneButtonDialog: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      avatar: app.globalData.userInfo.avatar
    })
    // this.loadWxPage()
    this.loadPoint()
    this.loadPromoter()
    this.data.canvasH = (wx.getSystemInfoSync().windowWidth / 750).toFixed(2)
    this.data.canvasHeight = 500 * this.data.canvasH
    this.createQrcodeClick()
    this.setData({
      canvasHeight: this.data.canvasHeight
    })
    app.userInfoReadyCallback = res => {
      if (app.globalData.token != null) {
        util.forwarding(options,app.globalData.token)
      }
    }
  },

  /**z
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadPromoter()
    this.loadPoint()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  onShareAppMessage: function () {
    return {
      title: app.globalData.mchName,
      desc: this.data.homeInfo.shareDescr,
      imageUrl: this.data.homeInfo.shareImage + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
      path: '/pages/index/index?xuid=' + app.globalData.userInfo.id// 路径，传递参数到指定页面。
    }
  },
  onShareTimeline: function () {
    return {
      title: app.globalData.mchName,
      desc: this.data.homeInfo.shareDescr,
      imageUrl: this.data.homeInfo.shareImage + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
      path: '/pages/index/index?xuid=' + app.globalData.userInfo.id// 路径，传递参数到指定页面。
    }
  },


  canvasClick() {
    var _this = this
    this.data.canvasType = true
    wx.getImageInfo({
      src: _this.data.cardInfo.qrCode, //网络图片路径
      success: res => {
        console.log(res.path, 's2')
        this.data.carvasQrCode = res.path; //图片临时本地路径
        wx.getImageInfo({
          src: util.proxyImage(app.APP_BASE_API,util.thumbnail('http://rzico.oss-cn-shenzhen.aliyuncs.com/img/fenxiang.png',400,400)), //网络图片路径
          success: res => {
            console.log(res.path, 's2')
            _this.data.carvasLogo = res.path; //图片临时本地路径
            this.setData({
              canvasType: this.data.canvasType,
              cardInfo: this.data.cardInfo
            })
             setTimeout(function () {
              _this.sharePosteCanvas()
            }, 1000)
          }
        })
      }
    })
   

  },
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas-show',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  createQrcodeClick() {
    if (app.globalData.token == null) {
      return;
    }
    createQrcode().then(res => {
      this.data.qrcode =  res.content 
      this.createImageClick()
    }).catch(error => {

    })
  },
  createImageClick() {
    let data =  this.data.qrcode
    this.data.cardInfo.qrCode = app.APP_BASE_API + '/zxing/createImage?mchId='+app.globalData.mchId+'&data='+encodeURIComponent(data)
    console.log(this.data.cardInfo.qrCode)
    this.setData({
      cardInfo: this.data.cardInfo
    })
  },
  cancleCanvasClick() {
    this.data.canvasType = false
    this.setData({
      canvasType: this.data.canvasType
    })
  },
  sharePosteCanvas: function () {
    var _this = this
    wx.showLoading({
        title: '生成中...',
        mask: true,
    })
    var canvasShow = wx.createCanvasContext("canvas-show")
    let ctx = new css2canvas(canvasShow)
    var canvasForm = [
      {
        type: "roundRect",
        x: 0,
        y: 0,
        width: 550,
        height: 500 ,
        background: "#ffffff",
        borderWidth: 1,
        borderRadius: 0,
        clip: false
      },
      {
        type: "image",
        imgUrl: _this.data.carvasQrCode,
        x: 20,
        y: 20,
        width: 400,
        height: 400
      },
      {
        type: "image",
        imgUrl: _this.data.carvasLogo,
        x: 60,
        y: 430,
        width: 40,
        height: 40
      },
      {
        type: "text",
        x: 112,
        y: 436,
        width: 320,
        content: '微信扫一扫，进入小程序',
        color: "#666666",
        fontSize: 24,
        textAlign: "left",
        overflow: "warp",
        maxLine: 1,
        lineHeight: 1
      },
    ]
    ctx
      .drawingView(canvasForm)
      .then(res => {
        console.log("绘制完成")
        wx.hideLoading();
      })
  },
  toDistribution(){
    wx.navigateTo({
      url: '/pages/member/integral/details',
    })
  },
})